package com.zc.portal.infra.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zc.commons.pojo.AuthenticatedUser;
import com.zc.portal.domain.dto.SysUser;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

@Component
public class RequestForwardFilter extends ZuulFilter {

    private static final String X_TOKEN = "x-token";

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        SecurityContext securityContext = SecurityContextHolder.getContext();
        SysUser sysUser = (SysUser) securityContext.getAuthentication().getPrincipal();
        try {
            String encryptToken = encryptToken(sysUser);
            context.addZuulRequestHeader(X_TOKEN, encryptToken);
        } catch (UnsupportedEncodingException e) {
            throw new ZuulException(e, 500, "不支持utf-8编码！");
        }
        return null;
    }

    /**
     * 公用的认证用户信息简单加密
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    private String encryptToken(SysUser sysUser) throws UnsupportedEncodingException {

        AuthenticatedUser user = new AuthenticatedUser();
        if (sysUser != null) {
            user.setUserCode(sysUser.getUserCode());
            user.setUserName(sysUser.getUserName());
            user.setUserId(sysUser.getUserId());
            user.setDeptId(sysUser.getDeptId());
            user.setPostCode(sysUser.getPostCode());
        }
        String userJsonStr = JSON.toJSONString(user);
        byte[] bytes = userJsonStr.getBytes("utf-8");
        String encode = Base64.getEncoder().encodeToString(bytes);
        return encode;
    }
}
